#include <stdint.h>

#include "main.h"
#include "spi.h"
#include "dma.h"

#include "fx_spi.h"

#include "aoaoutil.h"

int fx_spi_init(void)
{
    MX_DMA_Init();
    MX_SPI1_Init();

    return 0;
}

int fx_spi_tr(uint32_t *write_data, uint32_t *read_data)
{
    uint8_t write_buffer[4] = {0};
    uint8_t read_buffer[4] = {0};

    aut_afromu32_be(write_buffer, *write_data);
    HAL_SPI_TransmitReceive_DMA(&hspi1, write_buffer, read_buffer, 4);
    while (HAL_SPI_GetState(&hspi1) == HAL_SPI_STATE_BUSY_TX_RX)
    {
        ;
    }
    *read_data = aut_atou32_be(read_buffer);

    return 0;
}

int fx_spi_tr_byte(uint8_t *write_data, uint8_t *read_data, uint16_t len)
{
    HAL_SPI_TransmitReceive_DMA(&hspi1, write_data, read_data, len);
    while (HAL_SPI_GetState(&hspi1) == HAL_SPI_STATE_BUSY_TX_RX)
    {
        ;
    }

    return 0;
}
